package controller

import (
	"backend/api"
	"backend/internal/service"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type UploadController struct {
	log          *zap.Logger
	mediaService *service.MediaService
}

func NewUploadController(log *zap.Logger, mediaService *service.MediaService) *UploadController {
	return &UploadController{
		log:          log,
		mediaService: mediaService,
	}
}

func (h *UploadController) UploadMedia(c *gin.Context) {
	// 获取单个文件
	file, err := c.FormFile("file")
	if err != nil {
		h.log.Error("获取文件失败", zap.Error(err))
		// Element UI期望的错误响应格式
		c.JSON(400, gin.H{"code": 1, "message": "获取文件失败"})
		return
	}

	// 获取额外参数
	fileType := c.PostForm("type")
	customFileName := c.PostForm("fileName")

	// 构建上传请求
	uploadReq := &api.UploadRequest{
		File: file,
	}

	// 设置文件名
	if customFileName != "" {
		uploadReq.FileName = customFileName
	} else {
		uploadReq.FileName = file.Filename
	}

	// 设置文件类型
	if fileType != "" {
		uploadReq.Type = fileType
	}

	// 调用服务保存文件（现在只支持单文件上传）
	result, err := h.mediaService.Save(c, uploadReq)
	if err != nil {
		h.log.Error("保存文件失败", zap.Error(err))
		// Element UI期望的错误响应格式
		c.JSON(500, gin.H{"code": 1, "message": "保存文件失败"})
		return
	}
	api.Success(c, result)
}
